// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Text.RegularExpressions;
using System.Text;

namespace SnapObjects.Data
{
    internal abstract class FunctionBuilderParser : SqlBuilderParser
    {
        public FunctionBuilderParser(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {
        }

        public override SqlStatement Parse(SqlBuildStatement statement)
        {
            var function = (FunctionBuildStatement)statement;

            var parser = _factory.GetSqlParser(function.StatementType);

            var isFirstParameter = true;

            var sb = new StringBuilder();

            sb.Append(function.SqlRaw);
            sb.Append(SqlWhitespaceToken.Whitespace);

            this.ParseBuildParameters(function);

            foreach (var parameter in function.Parameters)
            {
                if (!isFirstParameter)
                {
                    sb.Append(",");
                }
                else
                {
                    isFirstParameter = false;
                }

                sb.Append(SqlWhitespaceToken.Whitespace);
                sb.Append(parameter.ParameterName);
            }

            if (parser is SqlFunctionStatementParser functionParser)
            {
                return functionParser.Parse(sb.ToString(), function.ReturnType);
            }

            return parser.Parse(sb.ToString());
        }
    }
}
